package com.bjtu.ptsite.controller;

import com.bjtu.ptsite.model.InviteCode;
import com.bjtu.ptsite.model.Result;
import com.bjtu.ptsite.model.User;
import com.bjtu.ptsite.service.InviteCodeService;
import com.bjtu.ptsite.service.UserService;
import com.bjtu.ptsite.utils.JwtUtils;
import com.bjtu.ptsite.utils.UUIDUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 *
 */
@CrossOrigin
@Slf4j
@RestController
public class LoginController {
    private static final int IDENTIFICATION_NUMBER_LENGTH = 8;
    @Autowired
    private UserService userService;
    @Autowired
    private InviteCodeService inviteCodeService;
    private static final String ROLE_ADMINISTRATOR = "admin";

    /**
     * 登录
     * 登录控制器
     * 
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        System.out.println(user);
        User u = userService.login(user);
        if (u != null) {
            if(u.isBaned()==true && !ROLE_ADMINISTRATOR.equals(u.getRole())){
                return Result.error("您的账户已被封禁!");
            }
            Map<String, Object> map = new HashMap<>(4);
            map.put("id", u.getUserId());
            map.put("username", u.getUsername());
            map.put("identificationNumber", u.getIdentificationNumber());

            String jwt = JwtUtils.generateJwt(map);
            Map<String,String> response = new HashMap<>(4);
            response.put("token", jwt);
            response.put("role", u.getRole());

            if(u.isDailyAward()==true){
                userService.dailyAward(u);
            }
            return Result.success(response);
        }
        return Result.error("用户名或密码错误");
    }

    @PostMapping("/register")
    public Result register(@RequestBody Map<String, String> params) {
        // 获取参数
        String identificationNumber = params.get("identificationNumber");
        String password = params.get("password");
        String email = params.get("email");
        String inviteCode = params.get("inviteCode");
        String verificationCode = params.get("verificationCode");

        // 验证基础参数
        if (identificationNumber == null || password == null || email == null ||
                inviteCode == null || verificationCode == null) {
            return Result.error("参数不完整");
        }

        if (identificationNumber.length() != IDENTIFICATION_NUMBER_LENGTH) {
            return Result.error("账号应为" + IDENTIFICATION_NUMBER_LENGTH + "位数");
        }

        // 验证邀请码
        InviteCode validCode = inviteCodeService.validateInviteCode(inviteCode);
        if (validCode == null) {
            return Result.error("无效邀请码或已过期");
        }

        // 验证邮箱验证码
        if (!userService.verifyCode(email, verificationCode)) {
            return Result.error("验证码无效或与邮箱不匹配");
        }

        // 检查用户信息唯一性
        if (userService.isEmailExists(email)) {
            return Result.error("邮箱已被注册");
        }

        // 创建用户
        User newUser = new User();
        newUser.setPassword(password);
        newUser.setEmail(email);
        newUser.setIdentificationNumber(Integer.parseInt(identificationNumber));
        newUser.setAvatar("https://avatar-wzh.oss-cn-beijing.aliyuncs.com/51e0ff55-4166-4870-baad-fff1705cd3ea.png");
        userService.register(newUser);

        // 扣除邀请码次数
        if (!inviteCodeService.useInviteCode(inviteCode)) {
            log.error("邀请码扣除失败，code: {}", inviteCode);
        }

        return Result.success("注册成功");
    }

    @PostMapping("/registerVerification")
    public Result registerVerification(@RequestBody Map<String, String> params) {
        String email = params.get("email");
        String inviteCode = params.get("inviteCode");

        // 验证邀请码有效性
        if (inviteCodeService.validateInviteCode(inviteCode) == null) {
            return Result.error("无效邀请码");
        }

        //验证邮箱唯一性
        if (userService.isEmailExists(email)){
            return Result.error("该邮箱已被注册");
        }

        // 发送验证码
        userService.sendVerificationCode(email,0);
        return Result.success("验证码已发送");
    }
}
